package com.example.jiagoujiexiang.Service.impl;

import com.example.jiagoujiexiang.Exption.MD5Util;
import com.example.jiagoujiexiang.Exption.ServiceException;
import com.example.jiagoujiexiang.Mapper.subscribeDao;
import com.example.jiagoujiexiang.Service.adminService;
import com.example.jiagoujiexiang.Service.userService;
import com.example.jiagoujiexiang.entity.User;
import com.example.jiagoujiexiang.entity.subscribe;
import com.example.jiagoujiexiang.Mapper.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class userServiceimpl implements userService {

    private final  UserDao userDao;
    @Autowired
    public userServiceimpl(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public User getUserByNum(User user) {

        String MD5password = MD5Util.md5(user.getPassword());
        user.setPasswordSecret(MD5password);
        userDao.insertUser(user);
        User userif = userDao.getUserByNum(user.getUsername());

        if (userif == null) {
            if (user.getPassword().equals(user.getPasswordSecret())) {
                if (userDao.insertUser(user) == 1) {
                    return user;
                } else {
                    throw new ServiceException("插入用户数据失败");
                }
            }
        }
        return user;
    }

    @Override
    public User getUserByid(int user_id) {
        return userDao.getUserByid(user_id);
    }
    @CacheEvict(cacheNames = "UserList", allEntries = true)
    @Override
    public int deleteUser(int userId) {
        return userDao.deleteUser(userId);
    }
    @CachePut(cacheNames = "User",key = "#user.id")
    @Override
    public int updateUseradmin(User user) {
        return userDao.updateUseradmin(user);
    }

    @Override
    public User getUserByName(String name) {
        return userDao.getUserByNum(name);
    }

    @Override
    public User insertUser(User user) {

        User userEntity = userDao.getUserByNum(user.getUsername());
        if (userEntity == null) {
            throw new ServiceException("用户不存在");
        } else {
            String md5Password = MD5Util.md5(user.getPassword());
            if (!md5Password.equals(userEntity.getPassword())) {
                throw new ServiceException("密码错误");
            } else {
                return userEntity;
            }
        }
    }


    @Override
    public int updateuserde(User user,User user2) {
       return userDao.updateUser(user,user2);
    }
}
